//key: string
//value: [fn, fn]
class Event {
    map = new Map()
    on(eventName, callback){
        if(!this.map.has(eventName))this.map.set(eventName, [])
        this.getCallbacks(eventName).push(callback)
    }
    emit(eventName, ...args){
        if(!this.map.has(eventName))return;
        this.getCallbacks(eventName).forEach(callback=>callback(...args))
        this.clearUndefined(eventName)
    }
    remove(eventName, callback){
        if(!callback)this.map.set(eventName, [])
        let fns = this.map.get(eventName);
        let index = fns.indexOf(callback)
        if(index !== -1)fns.splice(index, 1)
    }
    getCallbacks(eventName){
        if(!this.map.has(eventName))return;
        return this.map.get(eventName)
    }
    setUndefined(eventName, callback){
        if(!this.map.has(eventName))return;
        let fns = this.map.get(eventName)
        for(let i = 0; i < fns.length; i++){
            if(fns[i] === callback){
                fns[i] = undefined
                break;
            }
        }
    }
    clearUndefined(eventName){
        if(!this.map.has(eventName))return;
        this.map.set(eventName, this.getCallbacks(eventName).filter(fn=>fn&&true))
    }
    once(eventName, callback){
        const onceCallback = (...args)=>{
            callback(...args)
            this.setUndefined(eventName, onceCallback)
        }
        this.on(eventName, onceCallback)
    }
}

let hub = new Event()
hub.once('event', console.log)
hub.once('event', console.log)
hub.emit('event', 1) //两个1
hub.emit('event', 2) //什么都没有